package com.wchen.project.zk.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

/**
 * @Desc:   使用 ZkClient 获取节点数据内容
 * 
 * @author: cww
 * @DateTime: 2020-01-20 19:20
 */

public class ZooKeeperGetDataByZkClient {
    public static void main(String[] args) throws Exception{
        String path = "/zk-book";
        ZkClient zkClient = new ZkClient("home:2181", 5000);
        zkClient.createEphemeral(path, "123");
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            /**
             * 监听节点的变动
             * 数据内容的变更或数据版本变更
             * @param fullParentPath    节点的全路径
             * @param data  节点数据
             * @throws Exception
             */
            @Override
            public void handleDataChange(String fullParentPath, Object data) throws Exception {
                System.out.println("Node " + fullParentPath + " changed, new data: " + data);
            }

            /**
             * 监听节点被删除
             * @param fullParentPath
             * @throws Exception
             */
            @Override
            public void handleDataDeleted(String fullParentPath) throws Exception {
                System.out.println("Node " + fullParentPath + " deleted." );
            }
        });

        System.out.println(path + " is exists :" + zkClient.exists(path));
        System.out.println("readData:" + zkClient.readData(path));
        // writeData 接口参数:expectedVersion 预期版本号，CAS替换思想
        zkClient.writeData(path, "456");
        Thread.sleep(1000);
        zkClient.delete(path);
        Thread.sleep(5000);
    }
}
